package top.qitun.bizz.cart.cartevent.service.impl;

import java.util.Collection;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.base.service.BaseServiceImpl;

import top.qitun.api.CatalogServiceAPI;
import top.qitun.api.OrderServiceAPI;
import top.qitun.bizz.cart.cartevent.dao.CartEventDao;
import top.qitun.bizz.cart.cartevent.entity.CartEvent;
import top.qitun.bizz.cart.cartevent.service.CartEventService;
import top.qitun.bizz.catalog.product.entity.ProductBO;
import top.qitun.cart.ShoppingCart;

/**
 * 
 * <br>
 * <b>功能：</b>CartEventService<br>
 */
@Service("cartEventService")
public class CartEventServiceImpl extends BaseServiceImpl implements CartEventService {
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private CartEventDao dao;
	
	@Autowired
	private CatalogServiceAPI catalogServiceAPI;
	
	@Autowired
	private OrderServiceAPI orderServiceAPI;

	public CartEventDao getDao() {
		return dao;
	}

	@Override
	public void checkout(Integer tableId) throws Exception {
		// Check available inventory
		ShoppingCart currentCart = null;
		currentCart = aggregateCartEvents(tableId);

		if (currentCart != null) {
					// Create a new order
			orderServiceAPI.createOrder(tableId, 2, currentCart.getLineItems());
		}
		//设置购物车中的事件状态为已经下单
	}

	// /**
	// * Get the shopping cart for the currently authenticated user
	// *
	// * @return an aggregate object derived from events performed by the user
	// * @throws Exception
	// */
	// public ShoppingCart getShoppingCart() throws Exception {
	// ShoppingCart shoppingCart = null;
	// Catalog catalog =
	// restTemplate.getForObject("http://catalog-service/v1/catalog",
	// Catalog.class);
	// shoppingCart = aggregateCartEvents(user, catalog);
	// return shoppingCart;
	// }

	/**
	 * Aggregate the cart events of a user and return a {@link ShoppingCart}
	 * object
	 *
	 * @param user
	 *            is the user to retrieve the shopping cart for
	 * @param catalog
	 *            is the catalog used to generate the shopping cart
	 * @return a shopping cart representing the aggregate state of the user's
	 *         cart
	 * @throws Exception
	 */
	public ShoppingCart aggregateCartEvents(Integer tableId) throws Exception {
		Collection<ProductBO> productCollection = catalogServiceAPI.queryProductByTableId(tableId).getDataSet();
		ShoppingCart shoppingCart = new ShoppingCart(productCollection);
		List<CartEvent> cartEventList =dao.getCartEventStreamByTable(tableId);
		cartEventList.stream()
		.forEach(cartEvent -> shoppingCart.incorporate(cartEvent));
		shoppingCart.getLineItems();
		return shoppingCart;
	}
}
